package com.example.shoppingdemo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import android.os.Bundle;

import com.example.shoppingdemo.Adapter.mFragmentAdpter;
import com.example.shoppingdemo.Fragment.ClassifyFragment;
import com.example.shoppingdemo.Fragment.SpecialTopicFragment;
import com.example.shoppingdemo.Fragment.HomeFragment;
import com.example.shoppingdemo.Fragment.MyFragment;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private TabLayout mtabLayout;
    private ViewPager2 mviewPager2;
    List<Fragment> fragments=new ArrayList<>();

    //用来存放标题的集合
    List<String> tilies=new ArrayList<>();
    //用来存放图像的集合
    List<Integer> icon=new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mtabLayout=findViewById(R.id.tablayout);
        mviewPager2=findViewById(R.id.viewpager2);
        //标题
        tilies.add("主页");
        tilies.add("分类");
        tilies.add("购物车");
        tilies.add("我的");
        //图标
        icon.add(R.drawable.ic_home);
        icon.add(R.drawable.ic_baseline_dashboard_24);
        icon.add(R.drawable.ic_shopping_cart);
        icon.add(R.drawable.ic_my);
        //Fragment
        fragments.add(new HomeFragment());
        fragments.add(new ClassifyFragment());
        fragments.add(new SpecialTopicFragment());
        fragments.add(new MyFragment());
        mtabLayout.setTabMode(TabLayout.MODE_FIXED);
        //实例化适配器
        mFragmentAdpter frAdpter=new mFragmentAdpter
                (getSupportFragmentManager()
                        ,getLifecycle(),fragments);
        //设置适配器
        mviewPager2.setAdapter(frAdpter);
        //TabLayout与ViewPager2进行关联
        new TabLayoutMediator(mtabLayout, mviewPager2, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                tab.setText(tilies.get(position));
                tab.setIcon(icon.get(position));
            }
        }).attach();
    }
}